package com.zx.config;


import com.alibaba.fastjson.JSON;

import com.zx.common.ResponseCommon;
import com.zx.config.annotation.IgnoredResponseBodyAdvice;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * <h2>通用响应结果处理</h2>
 */
@RestControllerAdvice  // 所有的RestController 都采用该配置
public class ResponseCommonDataAdvice implements ResponseBodyAdvice {
    // controller---》return data
    /**
     * 使用该封装的条件
     */
    @Override
    public boolean supports(MethodParameter method, Class converterType) {
        // 如果当前正在返回的controller方法标记了 自定义注解，则不启用通用响应配置
        if(method.getMethod().isAnnotationPresent(IgnoredResponseBodyAdvice.class)){
            return false;
        }
        return true;
    }

    /**
     * 对responseBody的具体处理
     * body  responseBody
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class cType, ServerHttpRequest request, ServerHttpResponse response) {
        ResponseCommon<Object> responseCommon = new ResponseCommon(0,"");
        if(body == null){
            return responseCommon;
            // 如果全局异常处理返回了对象
        }else if(body instanceof ResponseCommon){
            responseCommon = (ResponseCommon<Object>) body;
        }else {
            responseCommon.setData(body);
            responseCommon.setCode(200);
            responseCommon.setMessage("success");
        }
        // 如果当前的controller返回的是String的结果
        if(cType.isAssignableFrom(StringHttpMessageConverter.class)){
            return JSON.toJSONString(responseCommon);
        }
        return responseCommon;
    }
}
